#!/usr/bin/env node

const readline = require('readline');
const calculateEntropy = require('./calculateEntropy');
const validateProbabilities = require('./validateProbabilities');
const { error, log } = require('console');

const args = process.argv.slice(2);

const isValidInputFormat = (input) => {
  const hasCommas = input.includes(',');
  const hasSpaces = input.includes(' ');
  return (hasCommas && !hasSpaces) || (!hasCommas && hasSpaces);
};

const getProbabilitiesFromInput = (input) => {
  const probabilities = input.split(/,|\s+/).filter(Boolean).map(Number);
  if (probabilities.length < 2) {
    return { error: '概率数据少于两个！', probabilities: null };
  }
  if (!isValidInputFormat(input)) {
    return { error: '错误输入，请确保输入格式正确（只能使用逗号或空格分隔）。', probabilities: null };
  }

  if (probabilities.some(p => isNaN(p))) {
    return { error: '请输入数字！', probabilities: null };
  }

  if (probabilities.some(p => p <= 0 || p > 1)) {
    return { error: '请输入大于0且小于等于1的数字。', probabilities: null };
  }

  const sum = probabilities.reduce((acc, p) => acc + p, 0);
  if (sum < 1) {
    return { error: '概率空间不封闭，概率和小于1。', probabilities: null };
  }
  if (sum > 1) {
    return { error: '概率空间不封闭，概率和大于1。', probabilities: null };
  }


  return { error: null, probabilities };
};

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

let isWaitingForInput = false;

if (args.length > 0) {
  const { error, probabilities } = getProbabilitiesFromInput(args.join(' '));
  if (error) {
    console.error(error);
    console.error("请按任意键重新输入，或按(CTRL+D)退出");
    rl.prompt();
    isWaitingForInput = true;
  } else {
    processInput(probabilities);
  }
} else {
  rl.prompt();
  isWaitingForInput = true;
}

rl.on('line', (input) => {
  if (isWaitingForInput) {
    const { error, probabilities } = getProbabilitiesFromInput(input);
    if (error) {
      console.error(error);
      console.error('请输入信源概率分布:(ctrl+D退出输入)');
      rl.prompt();
    } else {
      processInput(probabilities);
    }
  }
});

function processInput(probabilities) {
  if (!validateProbabilities(probabilities)) {
    console.error('Probabilities must sum up to 1.');
    console.error("请按任意键重新输入，或按(CTRL+D)退出");
    rl.prompt();
    return;
  }

  console.log(`p: [${probabilities.join(', ')}]`);
  const entropy = calculateEntropy(probabilities);
  console.log(`Entropy H(p): ${entropy}`);
  rl.close();
}

rl.on('close', () => {
  console.log('程序已退出');
  process.exit(0);
});

process.on('SIGINT', () => {
  console.log('\n退出输入...');
  rl.close();
});